{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 图灵机器人\n",
    "\n",
    "图灵:一位伟大的数学家、逻辑学家，被誉为“计算机科学之父”，“人工智能之父”。\n",
    "\n",
    "图灵机器人是一家以语义和对话技术为核心的人工智能公司，在人工智能机器人领域拥有数百项核心专利。公司网站：http://www.turingapi.com/。　\n",
    "\n",
    "图灵机器人开放平台是北京光年无限科技旗下的个性化人工智能机器人开放平台。通过图灵机器人开放平台，软硬件产品开发者可快速为自己的产品接入一款具备个性化身份属性特征、满足不同场景多轮对话及上下文对话的人工智能机器人，实现产品的对话式交互。\n",
    "\n",
    "本节我们使用百度AI的语音识别、语音合成，加上图灵机器人公司的智能聊天机器人，制作一个真正智能的小派小派。\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 开始我们的实验\n",
    "\n",
    "(1)图灵机器人使用:\n",
    "\n",
    "图灵机器人注册方式参考:https://segmentfault.com/a/1190000013900291\n",
    "\n",
    "(2)使用我们的图灵机器人的前期准备:\n",
    "\n",
    "获取图灵机器人的api_key.\n",
    "\n",
    "接口地址:http://openapi.tuling123.com/openapi/api/v2\n",
    "\n",
    "(3)使用图灵机器人:\n",
    "\n",
    "import json\n",
    "import urllib.request\n",
    "\n",
    "api_url = \"http://openapi.tuling123.com/openapi/api/v2\"\n",
    "\n",
    "req = {\n",
    "    \"perception\":\n",
    "    {\n",
    "        \"inputText\":\n",
    "        {\n",
    "            \"text\": \"替换为给图灵机器人的信息\"\n",
    "        }\n",
    "    },\n",
    "\n",
    "    \"userInfo\": \n",
    "    {\n",
    "        \"apiKey\": \"替换为自己的的api_key\",\n",
    "        \"userId\": \"OnlyUseAlphabet\"\n",
    "    }\n",
    "}\n",
    "\n",
    "将字典格式的req编码为utf8\n",
    "req = json.dumps(req).encode('utf8')\n",
    "\n",
    "提交自己问题给图灵机器人，图灵机器人的回答在response_dic\n",
    "\n",
    "    http_post = urllib.request.Request(api_url, data=req, headers={'content-type': 'application/json'})\n",
    "    response = urllib.request.urlopen(http_post)\n",
    "    response_str = response.read().decode('utf8')\n",
    "    response_dic = json.loads(response_str)\n",
    "\n",
    "图灵机器人返回的文本内容\n",
    "response_dic['results'][0]['values']['text']\n",
    "\n",
    "返回参数定义在:https://www.kancloud.cn/turing/www-tuling123-com/718227\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "######################################################\n",
    "#\n",
    "# 先感受下智能小派,选择本cell，按shirt+enter键运行本模块\n",
    "#\n",
    "######################################################\n",
    "\n",
    "#!/usr/bin/env python\n",
    "# -*- coding: utf-8 -*-\n",
    "#\n",
    "# Copyright (c) 2020 Taste all Pi.\n",
    "#\n",
    "# Licensed under the GNU General Public License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "#   http://www.gnu.org/licenses/gpl-2.0.html\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License.\n",
    "\n",
    "#导入标准库\n",
    "import sys\n",
    "import os\n",
    "import time\n",
    "import json\n",
    "import urllib.request\n",
    "\n",
    "#导入自定义库\n",
    "sys.path.append('../baidu_api_lib')\n",
    "from baidu_speech_recognition import baidu_speech_2_word\n",
    "from baidu_sound import baidu_word_2_sound\n",
    "import voice_record\n",
    "\n",
    "\"\"\" 公开课版本的有限量的语音识别，必须更换为自己的api接口　\"\"\"\n",
    "SP_APP_ID = '20733318 '\n",
    "SP_API_KEY = 'DZiN4wGf2GE7zRZ3xmuIUaVY'\n",
    "SP_SECRET_KEY = 'cMgwc303sBz0bQ50yDFiKBH1ovb1vxrw'\n",
    "\n",
    "#图灵机器人api接口\n",
    "api_url = \"http://openapi.tuling123.com/openapi/api/v2\"\n",
    "\n",
    "#图灵机器人的api key 更换为自己的api key\n",
    "tuling_key = \"cdb5f9d27e54421a990bc9c82c0d9e19\"\n",
    "\n",
    "#与图灵机器人聊天\n",
    "def tuling_robot_func(speak_msg):\n",
    "    #填充发给图灵机器人的内容\n",
    "    req = {\n",
    "        \"perception\":\n",
    "        {\n",
    "            \"inputText\":\n",
    "            {\n",
    "                \"text\": speak_msg\n",
    "            },\n",
    "        },\n",
    "\n",
    "        \"userInfo\": \n",
    "        {\n",
    "            \"apiKey\": tuling_key,\n",
    "            \"userId\": \"OnlyUseAlphabet\"\n",
    "        }\n",
    "    }\n",
    "        # 将字典格式的req编码为utf8\n",
    "    req = json.dumps(req).encode('utf8')\n",
    "    \n",
    "    #给图灵机器人发送请求\n",
    "    http_post = urllib.request.Request(api_url, data=req, headers={'content-type': 'application/json'})\n",
    "    response = urllib.request.urlopen(http_post)\n",
    "    response_str = response.read().decode('utf8')\n",
    "    response_dic = json.loads(response_str)\n",
    "    \n",
    "    #返回图灵机器人的回答\n",
    "    return response_dic['results'][0]['values']['text']\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    try:\n",
    "        #传入百度AI的参数给语音识别模块\n",
    "        sp_2_wd = baidu_speech_2_word(SP_APP_ID, SP_API_KEY, SP_SECRET_KEY)\n",
    "        \n",
    "        #传入百度AI的参数给语音合成模块\n",
    "        word_2_sound = baidu_word_2_sound(SP_APP_ID, SP_API_KEY, SP_SECRET_KEY)\n",
    "        \n",
    "        while True:\n",
    "            #进行麦克风录音，每次录音6秒\n",
    "            voice_record.recording(\"repeater_raw.wav\", 6)\n",
    "\n",
    "            #将音频采样率更改为百度需要的16000\n",
    "            os.system('sox repeater_raw.wav -r 16000 repeater.wav')\n",
    "            \n",
    "            #对音频文件进行分析\n",
    "            msg = sp_2_wd.speech_2_word('repeater.wav')\n",
    "\n",
    "            \n",
    "            #语音识别正确，则进行语音合成和输出\n",
    "            if msg[\"err_no\"] == 0:\n",
    "                #输出语音识别后，转化的文字\n",
    "                print(msg[\"result\"][0])\n",
    "        \n",
    "                #与图灵机器人进行聊天\n",
    "                tuling_answer = tuling_robot_func(msg[\"result\"][0])\n",
    "                \n",
    "                #输出图灵机器人给出的答案\n",
    "                print(tuling_answer)\n",
    "\n",
    "                #进行语音合成\n",
    "                word_2_sound.trans_word_to_sound(tuling_answer,'repeater.wav')\n",
    "                \n",
    "                #播放合成的语音\n",
    "                os.system('mplayer ' + 'repeater.wav')\n",
    "\n",
    "        #删除临时文件\n",
    "        os.remove('repeater.wav')\n",
    "        os.remove('repeater_raw.wav')\n",
    "        \n",
    "    except KeyboardInterrupt:\n",
    "        #删除临时文件\n",
    "        os.remove('repeater.wav')\n",
    "        os.remove('repeater_raw.wav')\n",
    "        print(\"任务被终止了\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 让我们临摹代码，学习“语音识别”功能"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#导入标准库\n",
    "# import sys\n",
    "\n",
    "# import os\n",
    "\n",
    "# import time\n",
    "\n",
    "# import json\n",
    "\n",
    "# import urllib.request\n",
    "\n",
    "\n",
    "# #导入自定义库\n",
    "# sys.path.append('../baidu_api_lib')\n",
    "\n",
    "# from baidu_speech_recognition import baidu_speech_2_word\n",
    "\n",
    "# from baidu_sound import baidu_word_2_sound\n",
    "\n",
    "# import voice_record\n",
    "\n",
    "\n",
    "# \"\"\" 公开课版本的有限量的语音识别，必须更换为自己的api接口　\"\"\"\n",
    "# SP_APP_ID = '20733318 '\n",
    "\n",
    "# SP_API_KEY = 'DZiN4wGf2GE7zRZ3xmuIUaVY'\n",
    "\n",
    "# SP_SECRET_KEY = 'cMgwc303sBz0bQ50yDFiKBH1ovb1vxrw'\n",
    "\n",
    "\n",
    "# #图灵机器人api接口\n",
    "# api_url = \"http://openapi.tuling123.com/openapi/api/v2\"\n",
    "\n",
    "\n",
    "#图灵机器人的api key 更换为自己的api key\n",
    "# tuling_key = \"cdb5f9d27e54421a990bc9c82c0d9e19\"\n",
    "\n",
    "\n",
    "# #与图灵机器人聊天\n",
    "# def tuling_robot_func(speak_msg):\n",
    "\n",
    "#     #填充发给图灵机器人的内容\n",
    "#     req = {\n",
    "\n",
    "#         \"perception\":\n",
    "\n",
    "#         {\n",
    "\n",
    "#             \"inputText\":\n",
    "\n",
    "#             {\n",
    "#                 \"text\": speak_msg\n",
    "\n",
    "#             },\n",
    "\n",
    "#         },\n",
    "\n",
    "\n",
    "#         \"userInfo\": \n",
    "\n",
    "#         {\n",
    "#             \"apiKey\": tuling_key,\n",
    "\n",
    "#             \"userId\": \"OnlyUseAlphabet\"\n",
    "\n",
    "#         }\n",
    "\n",
    "#     }\n",
    "\n",
    "#         # 将字典格式的req编码为utf8\n",
    "#     req = json.dumps(req).encode('utf8')\n",
    "\n",
    "    \n",
    "#     #给图灵机器人发送请求\n",
    "#     http_post = urllib.request.Request(api_url, data=req, headers={'content-type': 'application/json'})\n",
    "\n",
    "#     response = urllib.request.urlopen(http_post)\n",
    "\n",
    "#     response_str = response.read().decode('utf8')\n",
    "\n",
    "#     response_dic = json.loads(response_str)\n",
    "\n",
    "    \n",
    "#     #返回图灵机器人的回答\n",
    "#     return response_dic['results'][0]['values']['text']\n",
    "\n",
    "\n",
    "# if __name__ == \"__main__\":\n",
    "\n",
    "#     try:\n",
    "\n",
    "#         #传入百度AI的参数给语音识别模块\n",
    "#         sp_2_wd = baidu_speech_2_word(SP_APP_ID, SP_API_KEY, SP_SECRET_KEY)\n",
    "\n",
    "        \n",
    "#         #传入百度AI的参数给语音合成模块\n",
    "#         word_2_sound = baidu_word_2_sound(SP_APP_ID, SP_API_KEY, SP_SECRET_KEY)\n",
    "\n",
    "        \n",
    "#         while True:\n",
    "\n",
    "#             #进行麦克风录音，每次录音6秒\n",
    "#             voice_record.recording(\"repeater_raw.wav\", 6)\n",
    "\n",
    "\n",
    "#             #将音频采样率更改为百度需要的16000\n",
    "#             os.system('sox repeater_raw.wav -r 16000 repeater.wav')\n",
    "\n",
    "            \n",
    "#             #对音频文件进行分析\n",
    "#             msg = sp_2_wd.speech_2_word('repeater.wav')\n",
    "\n",
    "            \n",
    "#             #语音识别正确，则进行语音合成和输出\n",
    "#             if msg[\"err_no\"] == 0:\n",
    "\n",
    "#                 #输出语音识别后，转化的文字\n",
    "#                 print(msg[\"result\"][0])\n",
    "\n",
    "        \n",
    "#                 #与图灵机器人进行聊天\n",
    "#                 tuling_answer = tuling_robot_func(msg[\"result\"][0])\n",
    "\n",
    "                \n",
    "#                 #输出图灵机器人给出的答案\n",
    "#                 print(tuling_answer)\n",
    "\n",
    "\n",
    "#                 #进行语音合成\n",
    "#                 word_2_sound.trans_word_to_sound(tuling_answer,'repeater.wav')\n",
    "\n",
    "                \n",
    "#                 #播放合成的语音\n",
    "#                 os.system('mplayer ' + 'repeater.wav')\n",
    "\n",
    "\n",
    "#         #删除临时文件\n",
    "#         os.remove('repeater.wav')\n",
    "\n",
    "#         os.remove('repeater_raw.wav')\n",
    "\n",
    "        \n",
    "#     except KeyboardInterrupt:\n",
    "\n",
    "#         #删除临时文件\n",
    "#         os.remove('repeater.wav')\n",
    "\n",
    "#         os.remove('repeater_raw.wav')\n",
    "\n",
    "#         print(\"任务被终止了\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 课后练习\n",
    "\n",
    "(1)设置图灵计算机的机器人设置，配置适合自己的图灵机器人。\n",
    "\n",
    "(2)图机器人可以进行聊天、脑筋急转弯等对话，尝试聊聊呗"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
